package com.example.sachon;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.sachon.vo.BoardItem;
import com.example.sachon.vo.ChonInfo;

import android.graphics.Color;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SA1100 extends Activity implements IRefreshable{

	public void refresh() {
		// TODO Auto-generated method stub
		readServer();
	}
	public static final String NAME = "SA1100";

	public static final int SERVER_MODE_LOAD_BOARD_LIST = 1;

	private static final String SERVER_CHON_LIST_URL = Const.SERVER_BASE_URL
			+ "sa_board_list.jsp";

	protected static final String LOGTAG = "SA1100_";

	
	private List<ListContentItem> list;
	private ListContentListAdapter listAdapter;
	private ListView listview;
	private ProgressDialog progressbar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sa1100);
		
		Const.getInstance().addRefreshableTab(NAME, this);
		// 안드로이드 허니컴부터는 메인에서 Thread 사용을 못하는데 아래의 문장을 추가해주면 사요 가능.
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		readServer();

		/*
		 * title = (TextView) findViewById(R.id.title); title.setText(chon_name
		 * + " - 소 식 지" + " - " + phone_number);
		 */
	}

	private void readServer() {
		System.out.println("readserver");
		Thread thread = new Thread(new Runnable() {
			public void run() {

				try {
					String postURL = SERVER_CHON_LIST_URL;// Const.SERVER_BASE_URL+"chon_list.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();

					params.add(new BasicNameValuePair("board_id", "news"));
					params.add(new BasicNameValuePair("chon_id", Const
							.getInstance().chonInfo().getChon_id()));

					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient()
							.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity,
								"UTF-8");

						if (responseString.trim().equals("FAIL")) {
							mHandler.sendEmptyMessage(0);
						} else {
							Log.d(LOGTAG, " Response : "+responseString.trim());
							
							list = new ArrayList<ListContentItem>();

							JSONArray jsonArray = new JSONArray(responseString
									.trim());
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray
										.getJSONObject(i);
								ListContentItem listItem = new ListContentItem();

								listItem.setIdx(jsonObject.getString("idx"));
								listItem.setPhone_number(jsonObject
										.getString("phone_number"));
								listItem.setUser_name(jsonObject
										.getString("user_name"));
								listItem.setChon_id(jsonObject
										.getString("chon_id"));
								listItem.setTitle(jsonObject.getString("title"));
								listItem.setContent(jsonObject
										.getString("content"));
								listItem.setWr_dt(jsonObject.getString("wr_dt"));
								listItem.setPic_names(jsonObject
										.getString("pic_names"));
								listItem.setCnt(jsonObject
										.getString("cnt"));

								list.add(listItem);
							}

							mHandler.sendEmptyMessage(100);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		progressbar = ProgressDialog.show(this, null, "    Loading........");
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			progressbar.cancel();

			if (msg.what == 100) {// 상세 보기
				if (list.size() == 0) {
					Toast.makeText(SA1100.this, "DETAIL NO DATA",
							Toast.LENGTH_LONG).show();

					// 이전 Intent로 이동
					Intent intent = new Intent();
					setResult(RESULT_OK, intent);
					finish();

					// 리스트 뷰로 이동
				} else {
					listAdapter = new ListContentListAdapter(SA1100.this, list);
					listview = (ListView) findViewById(R.id.sa1100_board_list);
					listview.setAdapter(listAdapter);
					listview.setDivider(new ColorDrawable(Color.parseColor("#50C785")));
					listview.setDividerHeight(1);
					
					listview.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView parent, View v,
								int position, long id) {
							Intent intent = new Intent();
							intent.setClass(SA1100.this, SA1200.class);
							intent.putExtra("idx", list.get(position).getIdx());
							intent.putExtra("phone_number", list.get(position).getPhone_number());
							intent.putExtra("cnt", list.get(position).getCnt());
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
									| Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(intent);
						}
					});
				}
			} else if (msg.what == 200) {// 덧글쓰기
				// 덧글을 쓰레드 write 후 다시 읽어온다.
				readServer();
			} else if (msg.what == 0) {// 데이터 없음
				Toast.makeText(SA1100.this, "NO DATA.", Toast.LENGTH_LONG)
						.show();

				// 이전 Intent로 이동
				//Intent intent = new Intent();
				//setResult(RESULT_OK, intent);
				//finish();
			} else if (msg.what == -100) {// 에러
				Toast.makeText(SA1100.this, "ERROR", Toast.LENGTH_LONG).show();

				// 이전 Intent로 이동
				//Intent intent = new Intent();
				//setResult(RESULT_OK, intent);
				//finish();
			} else if (msg.what == -200) {// 에러
				Toast.makeText(SA1100.this, "삭제할 수 없습니다.", Toast.LENGTH_LONG)
						.show();

				// 이전 Intent로 이동
				//Intent intent = new Intent();
				//setResult(RESULT_OK, intent);
				//finish();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case 100:
			if (resultCode == RESULT_OK) {
				readServer();
			}
			break;
		case 200:
			if (resultCode == RESULT_OK) {
				readServer();
			}
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_sa1100, menu);
		return true;
	}
}
